import React from 'react';
import moment from "moment";
import UserModel from "../../../model/user";
import Admin from "../../../layout/Admin";
import {PageHeader, DatePicker, Table, Button, Modal, Select, Radio} from "antd";
import {downloadExl} from "../../../model/excel";
import {BaseUrl} from "../../../constant/constant";
import ActivitySummary from "../../../component/ActivitySummary/ActivitySummary";

const {RangePicker,} = DatePicker

class VisitorList extends React.Component {
    constructor(props) {
        super(props)
        this.model = new UserModel()
        this.froms = {
            // 'retou': '热投',
            // 'promotion_channel': '渠道包',
            // 'xiaomi': '小米',
            'promotion_channel': '360渠道',
            '360': '360应用市场',
            'retou': '公司渠道',
            'huawei': '华为应用市场',
            'xiaomi': '小米应用市场',
            'vivo': 'vivo应用市场',
            'oppo': 'oppo应用市场',
            'wandoujia': '豌豆荚应用市场',
            'google_tw': '谷歌',
            'kuaishou': '快手',
            'qutoutiao': '趣头条',
            'bilibili': 'B站',
            'aiqiyi': '爱奇艺',
            'cpa': 'cpa',
            'cpa_1': 'cpa_1',
            'cpa_2': 'cpa_2',
            'cpa_3': 'cpa_3',
            'cpa_4': 'cpa_4',
            'xmly': '喜马拉雅',
            'appstore': '苹果商店',
            'fhxw': '凤凰新闻',
            'weibo': '微博',
            other_1: '神马1',
            other_2: '神马2',
            other_3: '360',
        }
        this.state = {
            list: [],
            dayDiff: 3,
            start: moment().subtract(3, 'day').set({hour:0,minute:0,second:0,millisecond:0}),
            end: moment(),
            user: null,
            userBehavior: [],
            modal: {
                behavior: false,
            },
            froms: [],
            from: 1,
            total: 0,
            activated: 0,
            // start: 0,
            // end: 0,
        }
    }

    componentDidMount() {
        this.visitorList()
    }

    excel = () => {
        let data = [...this.state.list]
        const froms = this.state.froms
        if (froms.length > 0) {
            data = data.filter(value => this.state.froms.includes(value.From))
        }
        data = data.map(value => ({...value, From: this.froms[value.From]}))
        downloadExl(data)
    }

    downloadExcel = () => {
        this.model
            .excel()
            .then((res) => {
                console.log(res)
            })
    }

    onDateRangeChange = (value) => {
        let [start, end,] = value
        const dayDiff = end.diff(start, 'day')
        this.setState({
            start: start,
            end: end,
            dayDiff,
        }, () => {
            this.visitorList()
            this.appActivate()
        })
    }

    onUserBehaviorClick = (user) => {
        this.setState({
            user,
        }, () => {
            this.model
                .userBehavior({Uid: user.Mac})
                .then((resp) => {
                    if (resp.data.ok) {
                        let data = resp.data.ok
                        let userBehavior = data.map(dayData => {
                            const {
                                Date: date,
                                Handle: list,
                            } = dayData
                            let behavior = {}
                            list.map(v => {
                                if (behavior[v]) {
                                    behavior[v] += 1
                                } else {
                                    behavior[v] = 1
                                }
                            })
                            return {
                                date,
                                behavior,
                            }
                        })
                        this.setState({
                            userBehavior,
                        })
                    }
                })
                .then(() => {
                    this.setState({
                        modal: {
                            ...this.state.modal,
                            behavior: true,
                        }
                    })
                })
        })
    }

    visitorList() {
        this.model.visitorList({
            starttime: parseInt(this.state.start.format('X')),
            endtime: parseInt(this.state.end.format('X')),
        }).then(res => {
            const list = res.data.ok.sort((a, b) => b.Logint - a.Logint)
            this.setState({
                list,
            })
        })
    }

    appActivate = () => {
        const params = {
            Startt: parseInt(this.state.start.format('X')),
            Endt: parseInt(this.state.end.format('X')),
            From: this.state.from,
        }
        this.model
            .appActivate(params)
            .then(res => {
                if (res.data.ok) {
                    this.setState({
                        total: res.data.all,
                        activated: res.data.jihuo,
                    })
                }
            })
    }

    callModal = (key) => {
        this.setState({
            modal: {
                ...this.state.modal,
                [key]: true,
            }
        })
    }


    onModalCancel = (key) => {
        this.setState({
            modal: {
                ...this.state.modal,
                [key]: false,
            }
        })
    }

    onFromsSelectChange = (value) => {
        this.setState({
            froms: [...value,]
        })
    }

    callAppActivateModal = () => {
        this.appActivate()
        this.callModal('appActivate')
    }

    onActivateRadioChange = (value) => {
        console.log(value)
    }

    render() {
        let list = this.state.list
        const froms = this.state.froms
        if (froms.length > 0) {
            list = list.filter(record => froms.includes(record.From))
        }
        const userBehavior = this.state.userBehavior

        const defaultRender = (text) => text
        const timeRender = (time) => moment(new Date(time * 1000)).format('YYYY年MM月DD月 HH:mm ')
        const actionRender = (text, user) => {
            return <div>
                <a onClick={() => {this.onUserBehaviorClick(user)}}>用户行为</a>
            </div>
        }
        const columns = [
            // Mac       string
            // Logint    int64
            // From      string
            // Brand     string   //手机品牌
            // PhoneType string   //手机型号

            {
                title: '设备号',
                render: defaultRender,
                dataIndex: 'Mac',
            },
            {
                title: '登陆时间',
                render: timeRender,
                dataIndex: 'Logint',
                sorter: (a, b) => a.Logint - b.Logint
            },
            {
                title: '首次登陆',
                render: timeRender,
                dataIndex: 'FirstLogint',
                sorter: (a, b) => a.FirstLogint - b.FirstLogint
            },

            {
                title: '总登陆次数',
                render: defaultRender,
                dataIndex: 'Total',
            },
            {
                title: '来源',
                render: (text) => {
                    const m = this.froms
                    return <span>
                        {m[text]}
                    </span>
                },
                dataIndex: 'From',
            },
            {
                title: '渠道包',
                render: defaultRender,
                dataIndex: 'Pac',
            },
            {
                title: '品牌',
                render: defaultRender,
                dataIndex: 'Brand',
            },
            {
                title: '机型',
                render: defaultRender,
                dataIndex: 'PhoneType',
            },

            {
                title: '操作',
                render: actionRender,
            },
        ]
        const table = <Table
            dataSource={list}
            columns={columns}
            rowKey={(record, index) => index}
        />


        return <>

            <Modal
                visible={this.state.modal.appActivate}
                maskClosable={true}
                onCancel={() => this.onModalCancel('appActivate')}
                footer={null}
            >
                <p>激活统计</p>
                <RangePicker
                    showTime
                    style={{marginBottom: '16px'}}
                    defaultValue={[
                        // moment().subtract(3, 'day'),
                        // moment(),
                        this.state.start,
                        this.state.end,
                    ]}
                    onChange={(value) => {
                        this.onDateRangeChange(value)
                    }}
                />
                <div>
                    <Radio.Group onChange={this.onActivateRadioChange} value={this.state.from}>
                        <Radio value={1}>aso</Radio>
                    </Radio.Group>
                </div>
                <p style={{marginTop: '8px',}}>总数：{this.state.total}</p>
                <p>激活数：{this.state.activated}</p>
            </Modal>

            <Modal
                visible={this.state.modal.behavior}
                maskClosable={true}
                onCancel={() => this.onModalCancel('behavior')}
                width='80%'
            >
                {userBehavior.map(data => {
                    let {
                        date,
                        behavior,
                    } = data
                    return <div key={date}>
                        <p>{date}</p>
                        <ActivitySummary activity={behavior} />
                    </div>
                })}
            </Modal>
            <Admin>
                <div className='list-container'>
                    <PageHeader title='用户统计'/>
                    <RangePicker
                        showTime
                        style={{marginBottom: '16px'}}
                        defaultValue={[
                            // moment().subtract(3, 'day'),
                            // moment(),
                            this.state.start,
                            this.state.end,
                        ]}
                        onChange={(value) => {
                            this.onDateRangeChange(value)
                        }}
                    />
                    <span style={{margin: '0 8px',}}>选中共 {this.state.dayDiff} 日，用户总数： {list.length} 个</span>
                    <a
                        style={{marginLeft: '8px',}}
                        onClick={this.callAppActivateModal}
                    >激活统计</a>
                    <div
                        style={{marginBottom: '16px'}}
                    >
                        <Button onClick={this.excel} style={{marginRight: '8px',}}>
                            选中时间导出excel
                        </Button>
                        <a href={BaseUrl + 'download/youke.xlsx'} download='youke.xlsx'>
                            <Button>全部用户导出excel</Button>
                        </a>
                    </div>
                    <Select
                        mode="multiple"
                        // disabled
                        style={{ width: '50%', marginBottom: '8px',}}
                        placeholder="筛选来源"
                        // value={this.state.froms}
                        onChange={this.onFromsSelectChange}
                    >
                        {Object.entries(this.froms).map(([from, label]) => <Select.Option key={from} value={from}>{label}</Select.Option>)}
                    </Select>
                    {table}
                </div>
            </Admin>
        </>

    }
}

export default VisitorList

